package com.scs.application.modules.adm.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.SerialKeys;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.flow.FlowContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.adm.entity.MatrApply;
import com.scs.application.modules.adm.entity.MatrApplyItem;
import com.scs.application.modules.adm.entity.MatrAudit;
import com.scs.application.modules.adm.mapper.MatrApplyItemMapper;
import com.scs.application.modules.adm.mapper.MatrApplyMapper;
import com.scs.application.modules.adm.mapper.MatrAuditMapper;
import com.scs.application.modules.adm.service.MatrApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 耗材准入申请单 服务实现类
 * </p>
 */
@Service
public class MatrApplyServiceImpl extends BaseServiceImpl<MatrApplyMapper, MatrApply> implements MatrApplyService {
    @Autowired
    private MatrApplyItemMapper matrApplyItemMapper;
    @Autowired
    private MatrAuditMapper matrAuditMapper;
    @Override
    public boolean saveOrUpdate(MatrApply entity) {
        if (StringUtils.isBlank(entity.getBusKey())){
            entity.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.MATR_APPLY_KEY));
        }
        return super.saveOrUpdate(entity);
    }
    /**
     * @Description：流程前校验
     */
    @Override
    protected void beforeHandleFlowChange(FlowContext flowContext, MatrApply entity) {
        super.beforeHandleFlowChange(flowContext, entity);
        String buttonKey = flowContext.getButtonKey();
        // 提交审核，不允许空明细提交
        if ("submit".equalsIgnoreCase(buttonKey)) {
            Integer count = matrApplyItemMapper.selectCount(Wrappers.<MatrApplyItem>query().eq("apply_id", flowContext.getBusId()));
            if (count == null || count == 0) {
                throw new BusinessException("请添加申请耗材信息后，再提交");
            }
        } else  if ("cancel".equalsIgnoreCase(buttonKey)) { //取消操作
            List<MatrApplyItem> matrApplyItems = matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("apply_id", flowContext.getBusId()).isNotNull("audit_id"));
            if (matrApplyItems != null && matrApplyItems.size() > 0) {
                MatrAudit matrAudit =matrAuditMapper.selectById(matrApplyItems.get(0).getAuditId());

                throw new BusinessException("取消申请失败，申请明细已进入准入审批<br>审批单号:%s<br>品名:%s<br>品规:%s<br>厂商:%s",
                        matrAudit.getBusKey(),
                        matrApplyItems.get(0).getMatrName(),
                        matrApplyItems.get(0).getMatrSpec(),
                        matrApplyItems.get(0).getMfgName());
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            //删除子表
            List<MatrApplyItem> matrApplyItems = matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().select("id").eq("apply_id", id));
            if (matrApplyItems != null && matrApplyItems.size() >0) {
                matrApplyItemMapper.deleteBatchIds(matrApplyItems.stream().map(o -> o.getId()).collect(Collectors.toList()));
            }

        }
        return super.removeCascadeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MatrApply copy(String id) {
        if (StringUtils.isBlank(id)) throw new BusinessException("缺少参数【id】");
        MatrApply matrApply =baseMapper.selectById(id);
        if (matrApply == null) throw new BusinessException("所操作的单子已被删除，请刷新重试");
        matrApply.setId(null).setGmtCreate(LocalDateTime.now());
        matrApply.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.MATR_APPLY_KEY));
        matrApply.setFlowStatus("start").setFlowModified(null).setFlowModifier(null);
        this.save(matrApply);

        List<MatrApplyItem> matrApplyItems = matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("apply_id", id));
        if (matrApplyItems != null && matrApplyItems.size() > 0) {
            for(int i=0; i<matrApplyItems.size();i++)  {
                matrApplyItems.get(i).setId(null);
                matrApplyItems.get(i).setApplyId(matrApply.getId()).setAuditFlowStatusText(null).setAuditId(null).setAuditItemId(null);
                matrApplyItems.get(i).setSupplierCode(null).setSupplierName(null).setSkuPricePurchase(0d).setSkuPriceSell(0d).setSkuOfficialPriceSrc(null).setBidNo(null);
                matrApplyItemMapper.insert(matrApplyItems.get(i));
            }
        }
        return matrApply;
    }
}
